const mongoose = require('mongoose');
const Release = require('../models/release.model');
//新增数据
exports.create = function(req, res, next) {
    const release = new Release(req.body);
    release.save().then((data) => {
        res.json(data);
    });
}

exports.update = function(req, res, next) {
    const id = req.params.id;
    Release.findByIdAndUpdate(id, { $set: req.body }, { new: false }).then(data => {
        res.json(data); //这里返回的数据是修改之前的数据，不是修改之后的数据
    })
}

exports.remove = function(req, res, next) {
    const id = req.params.id;
    console.log(id);
    Release.findByIdAndDelete(id, (err, data) => {
        res.json(data);
    });
}

exports.list = function(req, res, next) {
        var page = req.body.page ? req.body.page : 1;
        var rows = req.body.rows ? req.body.rows : 5;
        var queryCondition = {}; //查询条件

        if (req.body.title && req.body.title.trim().length > 0) {
            title = req.body.title;
            queryCondition = {
                'title': new RegExp(title, 'i') //正则的查询条件，i是不区分大小写
            }
        }
        //分页
        // console.log(queryCondition, page, limit);
        Release.paginate(queryCondition, { page: +page, limit: +rows }, function(err, result) {
            result.rows = result.docs;
            delete result.docs;
            res.json(result);
        });


    }
    //获取单条数据
exports.getData = function(req, res, next) {
    var id = req.params.id;
    Release.findById(id).then(data => {
        res.json(data);
    })
}

exports.removes = function(req, res, next) {
    var ids = req.body.ids.split(',');
    if (ids.length > 0) {
        Release.remove({ _id: { $in: ids } }).then(data => {
            res.json({ 'message': 'delete ok', status: 200 })
        })
    }


}